<template>
	<!-- 不渲染内容，仅提供逻辑 -->
	<view style="display: none;" :prop="currentRadio" :change:prop="statsRender.watchCurrentRadio">
		<text :prop="playStatus" :change:prop="statsRender.watchPlayStatus"></text>
	</view>
</template>

<script>
export default {
	name: 'IcecastStatsFetcher',
	props: {
		// url: { type: String, required: true },
		currentRadio: { type: Object, required: true },
		playStatus: { type: String, required: true }
	},
	methods: {
		updateIcyData(data) {
			this.$emit('update', data); // 与原逻辑保持一致
		},
	},
};
</script>

<script module="statsRender" lang="renderjs">
	import IcecastMetadataStats from 'icecast-metadata-stats';

	export default {
		data() {
			return { currentRadio: null };
		},
		mounted() {
			this.statsInstance = null;
		},
		unmounted() {
			console.log('IcecastStatsFetcher退出了');
			this.stopListener();
		},
		methods: {
			watchCurrentRadio(newVal,oldVal) {
				// console.log('电台改变了：', newVal);
				this.currentRadio = newVal;
				this.restartListener();
			},
			watchPlayStatus(newVal) {
				console.log('状态变化：', newVal);
				if (newVal === 'playing' || newVal === 'loading') {
					this.startListener();
				} else {
					this.stopListener();
				}
			},
			startListener() {
				this.stopListener(); // 清理旧实例
				const owner = this.$ownerInstance;
				const url = this.currentRadio?.url;
				const hls=this.currentRadio?.hls;
				if(hls){
					console.log('电台属于hls,不执行监听');
					return;
				}
				let failCount = 0;
				const MAX_FAILS = 3;
				this.statsInstance = new IcecastMetadataStats(url, {
					interval: 30,
					sources: ['icy', 'ogg'], // 支持 ICY 和 Ogg
					onStats: (stats) => {
						const result = this.parseStats(stats);
						if(!result){
							failCount++;
							console.warn('获取icy数据失败，第'+failCount+'次了')
							if (failCount >= MAX_FAILS) {
								console.warn('连续失败，停止轮询');
								this.stopListener();
								owner && owner.callMethod('updateIcyData', { song: '', cover: '', stopped: true });
							}
						}else{
							failCount=0;
						}
						if (result?.song) {
							if (result.cover && result.cover.startsWith('http')) {
								try {
									fetch(result.cover)
										.then(res => res.json())
										.then(json => {
											const cover = json.eventImageUrlSmall || result.cover;
											owner&&owner.callMethod('updateIcyData', {
												song: result.song,
												cover
											});
										})
										.catch(err => {
											console.warn('封面获取失败:', err);
											owner&&owner.callMethod('updateIcyData', result);
										});
								} catch (err) {
									console.warn('封面获取异常:', err);
									owner&&owner.callMethod('updateIcyData', result);
								}
							} else {
								owner&&owner.callMethod('updateIcyData', result);
							}
						}
					},
				});

				this.statsInstance.start();
			},
			stopListener() {
				if (this.statsInstance) {
					this.statsInstance.stop();
					this.statsInstance = null;
				}
			},
			restartListener() {
				const status = this.$props.playStatus;
				if (status === 'playing' || status === 'loading') {
					this.startListener();
				}
			},
			parseStats(stats) {
				if (!stats) return null;
				// 优先使用 ICY，其次 Ogg
				if (stats.icy?.StreamTitle) {
					return {
						song: stats.icy.StreamTitle,
						cover: stats.icy.StreamUrl || ''
					};
				}
				if (stats.ogg?.TITLE) {
					return {
						song: stats.ogg.TITLE + ' - ' + stats.ogg.ARTIST,
						cover: stats.ogg.ALBUM || ''
					};
				}
				return null;
			}
		},
	};
</script>